package com.kust.smarhome.background.service.impl;

import com.kust.smarhome.background.model.User;
import com.kust.smarhome.background.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private IUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getByUsername(username);

        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码不正确");
        }

        String[] auth = {"admin"};

        UserDetails u = org.springframework.security.core.userdetails
                .User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .accountLocked(false)
                //getEnabled返回值为1,和0比较结果为false,既可用
                .disabled(user.getPower() != 1)
                .authorities(auth)//赋予当前登录用户权限
                .build();

        return u;
    }

    public List<GrantedAuthority> getUserAuthority(Integer userId) {
        User user = userService.getById(userId);

        String authority = userService.getUserAuthorityInfo(user.getId());

        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }

}
